<?php
namespace app\user\event\listeners\user;

use think\facade\Db;
use app\user\logic\user\Expenditure as ExpenditureLogic;
use app\user\logic\user\ExpenditureFlow;

/**
 * 用户消费
 */
class Expenditure
{
    public static function handle($param)
    {
        // 参数
        $order_sub_no   = $param['order_sub_no'];   // 子订单号
        $user_id        = $param['user_id'];   // 消费用户
        $num            = $param['num'];       // 消费金额
        // $type    = $param['product'];      // 消费类型
        // $rel_id  = $param['rel_id'];    // 如：course表ID，vip_config表ID，recharge_config表ID，等
        // $note    = $param['note'];      // 备注

        // 已交易
        $done_trade = app(ExpenditureFlow::class)->where('order_sub_no', $order_sub_no)->findOrEmpty();

        if ( $done_trade->isEmpty() ) {
            $exist      = app(ExpenditureLogic::class)->where('user_id', $user_id)->findOrEmpty();

            Db::startTrans();
            if ( $exist->isEmpty() ) {
                $exist = app(ExpenditureLogic::class)::create([
                    'user_id' => $user_id,
                    'num'     => $num,
                ]);
                $re = $exist->isEmpty() ? 0 : 1;
            } else {
                $exist->num += $num;
                $re = $exist->save();
            }

            $res = app(ExpenditureFlow::class)::create($param);

            if ( !$re || $res->isEmpty() ) {
                Db::rollback();
            } else {
                Db::commit();
            }
        }
    }

}
